package com.yanmushi.ms.webconsole.controller;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther yinlei
 * @date 2018/1/22
 * @since 1.0.0
 */
@Controller
public class IndexController {
    @RequestMapping("index")
    public String index(HttpSession session, ModelMap map, String token) throws IOException {

        if (session.getAttribute("user") == null) {
            return "redirect:http://localhost:8080/oauth/authorize?client_id=web-console&response_type=code&redirect_uri=http://localhost:8081/accept/code&scope=read";
        }

        map.put("token", token);

        return "index";
    }

    @ResponseBody
    @RequestMapping("read")
    public String read(@RequestParam("token") String token) throws IOException {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet("http://localhost:8082/dlc?token=" + token);
        HttpResponse resp = client.execute(get);
        if (resp.getStatusLine().getStatusCode() == 200) {
            return IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
        } else {
            return resp.getStatusLine().getStatusCode() + "";
        }
    }
}
